from mindspore.dataset import MnistDataset,vision,transforms
from download import download
import matplotlib.pyplot as plt 
from PIL import Image
import numpy as np

import numpy as np
# url = "https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/"\
#     "notebook/datasets/MNIST_Data.zip"
# path = download(url,"./",kind="zip",replace=True)
# train_dataset=MnistDataset('MNIST_Data/train')
# test_dataset=MnistDataset('MNIST_Data/test')
# image,label=next(train_dataset.create_tuple_iterator())
# print(image.shape,image.dtype)
# print(label)
#print(train_dataset.get_col_names())
#缩放
random_image=Image.open(r"D:\Users\Lenovo\Desktop\123.jpg")
rescale=vision.Rescale(1.0/123.0,0)
rescale_image=rescale(random_image)
print(rescale_image)
#标准化
normalize=vision.Normalize(mean=(0.1307,),std=(0.3081,))
normalize_image=normalize(rescale_image)
print(normalize_image)

# # 可视化图片
# plt.figure(figsize=(5, 5))  # 设置画布大小
# # MNIST图片是单通道灰度图（形状为(28,28,1)），需要转换为(28,28)才能正常显示
# plt.imshow(image.asnumpy().squeeze(), cmap='gray')  # squeeze()去除单通道维度
# plt.title(f"Label: {label.asnumpy()}")  # 显示标签（对应的数字）
# plt.axis('off')  # 关闭坐标轴
# plt.show()  # 显示图片
def convert_format(img):
    hwc2chw=vision.HWC2CHW();
    img2=hwc2chw(img)
    return img

# 可视化对比
plt.figure(figsize=(15, 5))

# 显示原图
plt.subplot(1, 3, 1)
plt.imshow(random_image)
plt.title("原图")
plt.axis('off')

# 显示缩放后图像
plt.subplot(1, 3, 2)
plt.imshow(convert_format(rescale_image))
plt.title("缩放后 ([0,1]范围)")
plt.axis('off')

# 显示标准化后图像
plt.subplot(1, 3, 3)
# 标准化后的值可能超出[0,1]，通过vmin/vmax调整显示范围
plt.imshow(convert_format(normalize_image), vmin=-0.4242, vmax=2.8314)  # 基于mean和std计算的典型范围
plt.title("标准化后 (mean=0.1307, std=0.3081)")
plt.axis('off')

plt.tight_layout()
plt.show()